var Overview = function(){
	this.menu_name = 'Overview';
}

Overview.prototype.Refresh = function(){
	this.PopulateTable();
}

Overview.prototype.PopulateTable = function(){
	var period = $('select#frequency').val();
	var total_income = Math.round(this.GetTotalIncome()*period);
	var total_expense = Math.round(this.GetTotalExpense()*period);
	var total_savings = 0;
	var remainder = 0;
	if(total_income < total_expense){
		total_savings = total_income - total_expense;
	}
	else{
		remainder = total_income - total_expense;
		var goal_savings = Math.round(this.GetTotalSavings()*period);
		if(goal_savings > remainder){
			total_savings = remainder;
			remainder = 0;
		}
		else{
			total_savings = goal_savings;
			remainder = remainder - total_savings;
		}
	}
	
	$('td#income').html('$'+total_income);
	$('td#expense').html('$'+total_expense);
	$('td#saving').html('$'+total_savings);
	$('td#remainder').html('$'+remainder).css('color', (remainder < 0) ? 'red' : 'black');
}

Overview.prototype.PopulateSavings = function(){
	var $savings_table = $('table#savings');
	$.each( window.saving, function(key, item){
		var time_left = item.goal/(item.contribution/item.frequency);
		$('<tr><td>'+item.name+'</td><td>'+time_left+' days</td></tr>').appendTo($savings_table);
	});
}

Overview.prototype.GetTotalIncome = function(){
	var sum = 0;
	$.each( window.income, function(key, item){
		sum += (item.amount/item.frequency)*(1-(item.tax_rate/100));
	});
	return sum;
}

Overview.prototype.GetTotalExpense = function(){
	var sum = 0;
	$.each( window.expense, function(key, item){
		sum += item.amount/item.frequency;
	});
	return sum;
}

Overview.prototype.GetTotalSavings = function(){
	var sum = 0;
	$.each( window.saving, function(key, item){
		sum += item.contribution/item.frequency;
	});
	return sum;
}